#include <cstdlib>
#include <iostream>
#include <string>
#include <unistd.h>
#include"../../util.hpp"

void getData(std::string& data)// 接收到的数据
{
    std::string method = getenv("Method");
    std::cerr << "Method:" << getenv("Method") << std::endl;

    
    if (method == "GET")
    {
        data = getenv("SubmitAttribute");
        std::cerr << "SubmitAttribute:" << data << std::endl;
    }
    else if (method == "POST")
    {
        std::cerr << "Content-Length:" << getenv("ContentLength") << std::endl;

        while (true)
        {
            char buffer[1024];
            int n = read(0, buffer, sizeof(buffer) - 1);
            if (n == 0)
            {
                break; // 读完了
            }
            else if (n < 0)
            {
                std::cout << "read fail" << std::endl; // 读出错
                break;
            }
            else
            {
                buffer[n] = '\0';
                data += buffer;
            }
        }
        std::cerr << "data: " << data << std::endl;
    }
}

int main()
{
    std::cerr << "I am testCgi!" << std::endl;
    std::string data;
    getData(data);//获取数据

    //对数据进行处理(例如x=1&y=2)
    std::string str1;
    std::string str2;
    Util::cutString(data,str1,str2,"&");

    //使用数据进行某些操作获得结果(例如x+y)
    //.....

    std::string htmlContent = "<!DOCTYPE html>\n"
        "<html lang=\"en\">\n"
        "<head>\n"
        "    <meta charset=\"UTF-8\">\n"
        "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n"
        "    <title>我的简历</title>\n"
        "    <style>\n"
        "        body { font-family: Arial, sans-serif; background-color: #f4f4f9; margin: 0; padding: 0; color: #333; }\n"
        "        .container { width: 80%; margin: 50px auto; background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); text-align: center; }\n"
        "        h1 { color: #2c3e50; }\n"
        "        footer { margin-top: 30px; font-size: 1.2em; color: #7f8c8d; }\n"
        "    </style>\n"
        "</head>\n"
        "<body>\n"
        "    <div class='container'>\n"
        "        <h1>欢迎访问主页</h1>\n"
        "        <p>你的账号： " + str1 + "</p>\n"
        "        <p>你的密码： " + str2 + "</p>\n"
        "    </div>\n"
        "</body>\n"
        "</html>\n";

    //返回处理后的结果
    // std::cout<<str1<<std::endl;
    // std::cout<<str2<<std::endl;

    std::cout<<htmlContent<<std::endl;
    
    return 0;
}